<template>
  <div class="header-container">
    <div class="left-section">
      <span :class="collapseBtnClass" class="collapse-btn" @click="collapse"></span>
      <el-breadcrumb separator="/" class="breadcrumb">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item><b>{{currentPathName}}</b></el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-dropdown class="user-dropdown">
      <div class="user-info">
        <el-tooltip effect="dark" placement="top" :content="user.username">
          <span>{{ truncatedText }}</span>
          <i class="el-icon-arrow-down"></i>
        </el-tooltip>
      </div>

      <el-dropdown-menu slot="dropdown" class="dropdown-menu">
        <el-dropdown-item>
          <router-link to="/person" class="dropdown-item">个人信息</router-link>
        </el-dropdown-item>
        <el-dropdown-item>
          <router-link to="/password" class="dropdown-item">修改密码</router-link>
        </el-dropdown-item>
        <el-dropdown-item>
          <div class="dropdown-item" @click="logout">退出登录</div>
        </el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>
  </div>
</template>

<script>
import router from "@/router";

export default {
  name: "Header",
  props:{
    collapseBtnClass:String,
    user:Object
  },
  computed:{
    truncatedText() {
      if (this.user.username?.length > 8) {
        return this.user.username.substring(0, 8) + '...';
      }
      return this.user.username;
    },
    currentPathName(){
      return this.$store.state.currentPathName;
    }
  },
  methods:{
    collapse(){
      this.$emit('collapse')
    },
    logout(){
      this.request.post('/user/logout').then(res => {
        if(res.code === '200'){
          this.$store.commit('logout');
          this.$message.success('退出登录成功');
        }else{
          this.$message.error('退出登录失败');
        }
      })
    }
  }
}
</script>

<style scoped>
.header-container {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0,21,41,.08);
}

.left-section {
  display: flex;
  align-items: center;
}

.collapse-btn {
  font-size: 20px;
  cursor: pointer;
  margin-right: 15px;
}

.breadcrumb {
  display: inline-block;
}

.user-dropdown {
  cursor: pointer;
}

.user-info {
  display: flex;
  align-items: center;
  color: #606266;
}

.user-info .el-icon-arrow-down {
  margin-left: 5px;
}

.dropdown-menu {
  min-width: 120px;
  text-align: center;
}

.dropdown-item {
  text-decoration: none;
  color: #606266;
  font-size: 14px;
  padding: 8px 0;
  display: block;
}

.dropdown-item:hover {
  color: #409EFF;
}
</style>
